package com.example.task01_demo01;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Enumeration;

public class ContextServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.配置参数的获取
        ServletContext servletContext = getServletConfig().getServletContext();
        Enumeration<String> initParameterNames = servletContext.getInitParameterNames();
        while(initParameterNames.hasMoreElements()){
            String s = initParameterNames.nextElement();
            System.out.println(s+"对应的值为:"+servletContext.getInitParameter(s));
        }
        System.out.println("________________________________________________________");


        //2.相关路径的获取
        //本质上就是获取工程路径
        String contextPath = servletContext.getContextPath();
        System.out.println("获取上下文关联的路径信息为:"+contextPath); ///task01_demo01_

        //   /在服务器中被解析为: http://ip地址:端口号/工程名  获取实际路径信息
        //获取到的是部署工程路径信息  对应当前工程中的web目录
        String realPath = servletContext.getRealPath("/");
        System.out.println("获取到的实际路径信息为:"+realPath); //E:\Java\java train\javaweb\task01_demo01\target\task01_demo01-1.0-SNAPSHOT\
        System.out.println("________________________________________________________");


        //3.设置和获取属性信息
        servletContext.setAttribute("key","value");
        Object key = servletContext.getAttribute("key");
        System.out.println("根据参数指定的属性名获取到的属性值为:"+key); //value
        servletContext.removeAttribute("key");
        key = servletContext.getAttribute("key");
        System.out.println("根据参数指定的属性名获取到的属性值为:"+key); //null
    }
}
